package com.swotplus.admin.web.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swotplus.framework.web.BaseController;
import com.swotplus.admin.web.wrapper.EleTreeWrapper;
import com.swotplus.common.annotation.Log;
import com.swotplus.common.constant.UserConstants;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.common.enums.BusinessType;
import com.swotplus.common.utils.StringUtils;
import com.swotplus.common.utils.bean.BeanUtils;
import com.swotplus.framework.shiro.ShiroUtils;
import com.swotplus.system.sys.entity.SysDept;
import com.swotplus.system.sys.entity.SysUser;
import com.swotplus.system.sys.service.SysDeptService;
import com.swotplus.system.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 * 
 * @author hugang
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    private String prefix = "system/dept";

    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept()
    {
        return prefix + "/dept";
    }

    @RequiresPermissions("system:dept:list")
    @RequestMapping("/list")
    @ResponseBody
    public List<SysDept> list(SysDept dept)
    {
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        List<SysDept> deptList = sysDeptService.list(sysDeptQueryWrapper);
        return deptList;
    }

    @RequiresPermissions("system:dept:list")
    @RequestMapping("/listTreeGridData")
    @ResponseBody
    public Map listTreeGridData(SysDept dept)
    {
        Map retMap = new HashMap();
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(dept.getDeptName())){
            sysDeptQueryWrapper.eq("dept_name",dept.getDeptName());
        }
        sysDeptQueryWrapper.eq("del_flag",0);
        List<SysDept> deptList = sysDeptService.list(sysDeptQueryWrapper);
        retMap.put("msg","");
        retMap.put("code",0);
        retMap.put("data",deptList);
        retMap.put("count",deptList!=null?deptList.size():0);
        retMap.put("is",true);
        retMap.put("tip","操作成功");
        return retMap;
    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") String parentId, ModelMap mmap)
    {
        mmap.put("dept", sysDeptService.getById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysDept dept)
    {
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        sysDeptQueryWrapper.eq("dept_name",dept.getDeptName());
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(sysDeptService.count(sysDeptQueryWrapper)))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        SysDept sysDept=sysDeptService.getById(dept.getParentId());
        if(dept.getParentId()==0){
            dept.setAncestors("0");
        }else{
            dept.setAncestors(sysDept.getAncestors()+","+sysDept.getParentId());
        }
        dept.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(sysDeptService.save(dept));
    }

    /**
     * 修改
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") String deptId, ModelMap mmap)
    {
        SysDept dept = sysDeptService.getById(deptId);
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysDept dept)
    {
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        sysDeptQueryWrapper.eq("dept_name",dept.getDeptName());
        if (sysDeptService.count(sysDeptQueryWrapper)>0)
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        SysDept sysDept=sysDeptService.getById(dept.getId());
        BeanUtils.copyProperties(dept,sysDept);
        sysDept.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(sysDeptService.updateById(sysDept));
    }

    /**
     * 删除
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dept:remove")
    @RequestMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") String deptId)
    {
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        sysDeptQueryWrapper.eq("parent_id",deptId);

        QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<SysUser>();
        sysUserQueryWrapper.eq("dept_id",deptId);
        if (sysDeptService.count(sysDeptQueryWrapper) > 0)
        {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (sysUserService.count(sysUserQueryWrapper)>0)
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptService.removeById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(SysDept dept)
    {
        QueryWrapper<SysDept> sysDeptQueryWrapper=new QueryWrapper<>();
        sysDeptQueryWrapper.eq("dept_name",dept.getDeptName());
        if( sysDeptService.count()>0){
            return  UserConstants.DEPT_NAME_NOT_UNIQUE;
        }

        return UserConstants.DEPT_NAME_UNIQUE;
    }

    /**
     * 选择部门树
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap)
    {
        mmap.put("dept", sysDeptService.getById(deptId));
        return prefix + "/tree";
    }

     /**
     * 加载部门列表树
      */
    @GetMapping("/treeData")
    @ResponseBody
    public Map treeData()
    {
        Map retMap = new HashMap();
        List<Map<String, Object>> tree = sysDeptService.selectDeptTree(new SysDept());
        tree = EleTreeWrapper.getInstance().getTree(tree,"pId","id");
        retMap.put("code",0);
        retMap.put("data",tree);
        return retMap;
    }

}
